package com.blakequ.androidblemanager.ui;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blakequ.androidblemanager.R;
import com.blakequ.androidblemanager.service.MyService;
import com.blakequ.androidblemanager.utils.IntentUtils;
import com.blakequ.androidblemanager.utils.LocationUtils;
import com.blakequ.androidblemanager.widget.MyAlertDialog;
import com.blakequ.bluetooth_manager_lib.util.BluetoothUtils;
import com.tamsiree.rxkit.RxActivityTool;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;

import static com.blakequ.bluetooth_manager_lib.util.BluetoothUtils.REQUEST_ENABLE_BT;

public class BaseActivity extends AppCompatActivity {
    private String[] permissionList = {Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxActivityTool.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxActivityTool.finishActivity(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAllPermission();
    }

    /**
     * 检查权限
     * @return
     */
    public boolean checkPermission(){
        if (Build.VERSION.SDK_INT >= 23){
            boolean hasPermission = PermissionUtils.hasSelfPermissions(this, permissionList);
//            MainActivityPermissionsDispatcher.showCheckPermissionStateWithCheck(this);
            BasePagePermissionsDispatcher.showCheckPermissionStateWithPermissionCheck(this);
            if (!LocationUtils.isGpsProviderEnabled(this)){
                return false;
            }
            return hasPermission;
        }
        return true;
    }

    protected void checkAllPermission() {
        checkPermission();
        if (!Utils.isPermissionOpen(this)) {
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Utils.openPermissionSetting(BaseActivity.this);
                        }
                    })
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            finish();
                            RxActivityTool.AppExit(BaseActivity.this);
                        }
                    })
                    .setCancelable(false)
                    .setMessage("为了正常运行，需要授权通知栏权限")
                    .create();
            dialog.show();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!isIgnoringBatteryOptimizations()) {
                requestIgnoreBatteryOptimizations();
            }
        }
        checkBluetoothPermission();
    }


    //请求权限
    /**
     * 这个方法中写正常的逻辑（假设有该权限应该做的事）
     */
    @NeedsPermission({Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
            ,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showCheckPermissionState(){
        //检查是否开启位置信息（如果没有开启，则无法扫描到任何蓝牙设备在6.0）
        if (!LocationUtils.isGpsProviderEnabled(this)){
            showOpenLocationSettingDialog();
        }
        else{
            if (settingsDialog != null && settingsDialog.isShowing()) {
                settingsDialog.dismiss();
                settingsDialog = null;
            }
        }
    }

    /**
     * 弹出权限同意窗口之前调用的提示窗口
     * @param request
     */
    @OnShowRationale({Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForPermissionState(PermissionRequest request) {
        // NOTE: Show a rationale to explain why the permission is needed, e.g. with a dialog.
        // Call proceed() or cancel() on the provided PermissionRequest to continue or abort
        MyAlertDialog.showRationaleDialog(this, R.string.permission_rationale, request);
    }

    /**
     * 提示窗口和权限同意窗口--被拒绝时调用
     */
    @OnPermissionDenied({Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onPermissionStateDenied() {
        // NOTE: Deal with a denied permission, e.g. by showing specific UI
        // or disabling certain functionality
        Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 当完全拒绝了权限打开之后调用
     */
    @OnNeverAskAgain({Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onPermissionNeverAskAgain() {
        MyAlertDialog.showOpenSettingDialog(this, R.string.open_setting_permission);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        BasePagePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
    AlertDialog settingsDialog;
    /**
     * 打开位置信息
     */
    private void showOpenLocationSettingDialog(){
        if (settingsDialog != null && settingsDialog.isShowing()) {
            settingsDialog.dismiss();
            settingsDialog = null;
        }
        View view = LayoutInflater.from(this).inflate(R.layout.include_location_dialog, null);
        settingsDialog = MyAlertDialog.getViewDialog(this, view, R.string.ble_location_open, R.string.cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IntentUtils.startLocationSettings(BaseActivity.this, 11);
                        dialog.dismiss();
                    }
                },
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showReOpenLocationDialog();
                        dialog.dismiss();
                    }
                }, false);
        settingsDialog.show();
    }

    /**
     * 重新检查位置信息是否开启
     */
    private void showReOpenLocationDialog() {
        MyAlertDialog.getDialog(this, R.string.ble_location_not_open, R.string.ble_location_open, R.string.cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IntentUtils.startLocationSettings(BaseActivity.this, 12);
                        dialog.dismiss();
                    }
                },
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (BluetoothUtils.getInstance(this).isBluetoothIsEnable()) {
                restartApp();
            }
        }
    }

    /*
         校验蓝牙权限
        */
    private void checkBluetoothPermission() {
        if (!BluetoothUtils.getInstance(this).isBluetoothIsEnable()) {
            BluetoothUtils.getInstance(this).askUserToEnableBluetoothIfNeeded(this);
        }
    }

    protected void restartApp() {
        Intent intentService = new Intent(this, MyService.class);
        stopService(intentService);
        finish();
        RxActivityTool.finishAllActivity();
//                RxActivityTool.AppExit(MainPage.this);
        Intent intent = new Intent(BaseActivity.this, LoginPage.class);
        startActivity(intent);
    }
}
